package com.zenithsun.common.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 正则表达式相关
 * 
 * @author wanglei@enersun.com.cn
 */
public class RegExUtil {
	private static Logger log = LoggerFactory.getLogger(RegExUtil.class);
	public static void main(String[] args) {
		String s = "<img src=\"/csg_pic/zenithsun/news/images/2016/0707/5c404090155c40eb77e0015.JPG\" />";
		log.info(getImageFromContentByReg(s)+"");
	}

	/**
	 * 通过正则表达式获取内容中的图片标签
	 * 
	 * @return
	 */
	public static List<String> getImageFromContentByReg(String content) {
		List<String> imageList = new ArrayList<String>();
		// 找出IMG标签
		String regxpForImgTag = "<\\s*img\\s+([^>]*)\\s*>";
		Pattern pattern = Pattern.compile(regxpForImgTag);
		Matcher matcher = pattern.matcher(content);
		while (matcher.find()) {
			String path = matcher.group();
			path = getImageSrc(path);
			if (!imageList.contains(path)) {
				imageList.add(path);
			}
		}
		return imageList;
	}

	/**
	 * 获取IMG标签中的src属性
	 * 
	 * @param img
	 * @return
	 */
	private static String getImageSrc(String img) {
		String regxpForImaTagSrcAttrib = "src=\"([^\"]+)\"";
		Pattern pattern = Pattern.compile(regxpForImaTagSrcAttrib);
		Matcher matcher = pattern.matcher(img);
		while (matcher.find()) {
			String src = matcher.group();
			return src.substring(5, src.length() - 1);
		}
		return null;
	}

	/**
	 * 判断是否时间格式
	 * @param date
	 * @return boolean
	 */
	public static boolean isDate(String date) {
		String eL = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";
		Pattern p = Pattern.compile(eL);
		Matcher m = p.matcher(date);
		boolean b = m.matches();
		if (b) {
			log.info("格式正确");
		} else {
			log.error("格式错误");
		}
		return b;
	}
}
